<?php


namespace app\plugin\controller\article;


use app\common\controller\AppCommon;
use app\plugin\controller\article\service\OrderService;
use app\service\DiyLog;
use base\WeixinAgent;
use think\Controller;
use think\Request;

class Payment extends Controller
{
    protected $param = [];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->param = input();
    }

    public function notify()
    {
        DiyLog::file($this->param, 'article支付回调.log');
        if (empty($this->param['form'])) {
            data_return('请求不合法', -1);
        }

        $params = !empty($this->param['form']) ? $this->param['form'] : '';
        if (empty($params['payData']['outOrder'])) {
            data_return('单号缺失', -1);
        }
        $order = AppCommon::data_get('plugin_article_order', ['order_sn' => $params['payData']['outOrder']], 'id,aid');

        if (!$order) {
            data_return('订单不存在', -1);
        }
        $akey = 'uqhmv7c6qc';
        //todo 动态化
        $asecret = '11af5c27f5c8d5678a04cbqsf2620586';

        if ($params['sign'] == (new WeixinAgent())->get_sign($params, $asecret)) {
            if ($params['payData']['result_code'] == 'SUCCESS' && $params['payData']['return_code'] == 'SUCCESS') {
                $res = OrderService::update($params['payData']['outOrder'], [
                    'pay_price' => $params['payData']['total_fee'] / 100,
                    'pay_time' => strtotime($params['payData']['time_end']),
                    'up_time' => time(),
                    'status' => 1,
                    'pay_openid' => $params['payData']['openid'],
                    'trans_id' => $params['payData']['transaction_id'],
                    'pay_type' => 'wechat',
                ]);
                $article = AppCommon::data_get('plugin_article', ['aid' => $order['aid']], 'id,sale_count');
                AppCommon::data_update('plugin_article', ['aid' => $order['aid']], ['sale_count' => $article['sale_count'] + 1]);
                data_return($res['msg'], $res['code']);
            } else {
                data_return('支付失败', -1);
            }

        }
        data_return('非法提交', -1);
    }
}